package 课设;

import javax.sql.DataSource;
import java.sql.*;
public class db {
    Connection dbConn;
    Statement stateMent;

    String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public db() {
        //SQL Server 2005(及以上)JDBC驱动
        String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        //数据库SQL Server 2005(及以上) URL
        String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=blog_controller;encrypt=true;trustServerCertificate=true";
        String userName = "sa";//默认用户名
        String userPwd = "123456";//密码
        try {
            Class.forName(driverName); //Class.________(driverName);
            dbConn = DriverManager.getConnection(dbURL,userName,userPwd);//dbConn = DriverManager._________(dbURL,userName,userPwd);
            //如果连接成功 控制台输出Connection Successful!
            System.out.println("Connection Successful!");
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public int executeUpdate(String sql) throws SQLException {
        stateMent = dbConn.createStatement(); //statement = ______.createStatement();
        return stateMent.executeUpdate(sql);
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        stateMent = dbConn.createStatement();
        return stateMent.executeQuery(sql); //return statement._______(sql);
    }

    public void closeConn() throws SQLException {
        stateMent.close();
        dbConn.close();
    }
    public PreparedStatement PreparedStatement(String sql) throws SQLException{
        return dbConn.prepareStatement(sql);
    }

    public void close(Connection connection, PreparedStatement statement, ResultSet resultSet){
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

